//
//  MapSearchViewController.m
//  beautyAccompany
//
//  Created by xiaocankeji on 15/11/13.
//  Copyright © 2015年 xiaocankeji. All rights reserved.
//

#import "MapSearchViewController.h"
#import "SelectCityViewController.h"
#define  kSearchViewHeight 44
#define  kSelectLocationLabelHeight 60
#define  kCityBTWidth 60

//#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关所有的头文件

#define  cellAllHeight 200

@interface MapSearchViewController ()<BMKMapViewDelegate,BMKLocationServiceDelegate,BMKSuggestionSearchDelegate,BMKPoiSearchDelegate,BMKGeoCodeSearchDelegate,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,SelectCityViewControllerDelegate>//BMKGeoCodeSearchDelegate

@property (nonatomic, strong) BMKMapView *mapView;
@property (nonatomic, strong) BMKLocationService *locService;
@property (nonatomic, strong) BMKGeoCodeSearch *codeSearch;
@property (nonatomic, strong) BMKSuggestionSearch *searcher;//搜索联想词
@property (nonatomic, strong) BMKPoiSearch *poiSearch;

@property (nonatomic, strong) BMKPointAnnotation *userSelectPointAnnotation;

@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) UITableView *searchTableView;
@property (nonatomic, strong) NSArray  *searchArr;//联想到数组
@property (nonatomic, strong) NSMutableDictionary *searchDic;//联想的字典, title(key)对应坐标

@property (strong, nonatomic) UITextField *searchTextField;
@property (nonatomic, strong) UIButton *cityBt;
@property (nonatomic, strong) NSString *locationCity;
@property (nonatomic, assign) int keyboardHeight;
@property (nonatomic, strong) UILabel *selectLocationLabel;
@property (nonatomic, strong) NSString *myLocation;
@property (nonatomic, strong) NSString *mapPoiText;

@property BOOL userSelect;//用户自己选择的的标注,使用后立即改为NO

@end

@implementation MapSearchViewController


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [_mapView viewWillAppear];
    _mapView.delegate = self;
     _searcher.delegate = self;
    _poiSearch.delegate = self;
    _codeSearch.delegate = self;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [_mapView viewWillDisappear];
    _mapView.delegate = nil;
    _searcher.delegate = nil;
    _poiSearch.delegate = nil;
    _codeSearch.delegate = nil;
}
- (NSMutableDictionary *)searchDic
{
    if (_searchDic == nil) {
        _searchDic = [NSMutableDictionary dictionary];
    }
    return _searchDic;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"地点";
    self.view.backgroundColor = RGBA(222, 222, 222, 1);
    [self addViewSubView];
    UIBarButtonItem *rightItem  = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(rightItem)];
    rightItem.tintColor = [UIColor redColor];
    self.navigationItem.rightBarButtonItem = rightItem;
     //Do any additional setup after loading the view.
   
    //增加监听，当键盘出现或改变时收出消息
    
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWillShow:)
     
                                                 name:UIKeyboardWillShowNotification
     
                                               object:nil];
    
    
    
//    //增加监听，当键退出时收出消息
//    
//    [[NSNotificationCenter defaultCenter] addObserver:self
//     
//                                             selector:@selector(keyboardWillHide:)
//     
//                                                 name:UIKeyboardWillHideNotification
//     
//                                               object:nil];
}
//当键盘出现或改变时调用

- (void)keyboardWillShow:(NSNotification *)aNotification

{
    
    //获取键盘的高度
    
    NSDictionary *userInfo = [aNotification userInfo];
    
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    CGRect keyboardRect = [aValue CGRectValue];
    
    int height = keyboardRect.size.height;
    
//    if(self.searchTableView){
//        _searchTableView.contentSize = CGSizeMake(DeviceWidth, DeviceHeight -kSearchViewHeight-kNavigationBarHeight - height);
//    }
    self.keyboardHeight = height;
    
}


//当键退出时调用

- (void)keyboardWillHide:(NSNotification *)aNotification

{
    
    
    
}
- (void)rightItem
{
   
    
    if ([self.selectLocationLabel.text isEqualToString:@"定位中"]) {
        
        [HUD Prompt:@"请选择位置"];
        return;
    }
    
    if (self.cityBt.titleLabel.text.length&&self.selectLocationLabel.text.length){
        
        if([_delegate respondsToSelector:@selector(selectCity:Location:)]){
            
            [self.navigationController popViewControllerAnimated:YES];
            [_delegate selectCity:self.cityBt.titleLabel.text Location:self.selectLocationLabel.text];
        }
    }
    
    
    
}
#pragma mark UITableViewDataSource UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
        
        if (self.searchArr.count) {
            _searchTableView.hidden = NO;
        }else{
            _searchTableView.hidden = YES;
        }
        return self.searchArr.count;
    
    
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    
        static NSString *searchStr = @"searchCell";
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:searchStr];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:searchStr];
        }
        cell.textLabel.text = self.searchArr[indexPath.row];
        
        return cell;
    
    
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
        return 44;
    
    
    return 44;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
        NSString *str =self.searchArr[indexPath.row];
        [self searchTextLocationCity:self.cityBt.titleLabel.text content:str];
    
    
}
- (void)selectCityName:(NSString *)city
{
    [self.cityBt setTitle:city forState:UIControlStateNormal];
    _selectLocationLabel.text = @"";
}
- (void)clickCityBt
{
    SelectCityViewController *selectCVC = [[SelectCityViewController alloc] init];
    selectCVC.locationCity = self.locationCity;
    selectCVC.delegate = self;
    [Utils pushTabbarHidden:selectCVC Selfvc:self];
}
- (void)addViewSubView
{
    _searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, kSearchViewHeight)];
    _searchView.backgroundColor = RGBA(188, 188, 188, 0.99);
    _searchView.layer.masksToBounds = YES;
    [self.view addSubview:_searchView];
    
     _poiSearch = [[BMKPoiSearch alloc]init];
    //搜索
   
    
    
    UIView *borderView = [[UIView alloc] initWithFrame:CGRectMake(5,(kSearchViewHeight-30)/2, DeviceWidth-10, 30)];
    borderView.layer.cornerRadius = 5;
    borderView.layer.borderWidth = 0.5;
    borderView.layer.borderColor = [[UIColor clearColor] CGColor];
    borderView.backgroundColor = [UIColor whiteColor];
    
    _cityBt = [UIButton buttonWithType:UIButtonTypeCustom];
    _cityBt.frame = CGRectMake(0, 0 , kCityBTWidth, 30);
    _cityBt.backgroundColor = [UIColor clearColor];
    [_cityBt setTitle:@"广州市" forState:UIControlStateNormal];
    [_cityBt setTitleColor:RGBA(88, 88, 88, 1) forState:UIControlStateNormal];
    _cityBt.titleLabel.font = kFont(13);
    [_cityBt addTarget:self action:@selector(clickCityBt) forControlEvents:UIControlEventTouchUpInside];
    [borderView addSubview:_cityBt];
    //定位后,反解码
   _codeSearch = [[BMKGeoCodeSearch alloc]init];
    
    
    UIImageView *seachImageView = [[UIImageView alloc] initWithFrame:CGRectMake(kCityBTWidth , 8, 14, 14)];
    seachImageView.image = [UIImage imageNamed:@"search-bar_search_icon"];
    [borderView addSubview:seachImageView];
    
    [_searchView addSubview:borderView];
    
    //百度搜索联想词
    _searcher = [[BMKSuggestionSearch alloc] init];
    
    
    self.searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(kCityBTWidth +  20, 0, DeviceWidth-20-10 - kCityBTWidth, 30)];
    
    self.searchTextField.returnKeyType = UIReturnKeySearch;
    self.searchTextField.backgroundColor = [UIColor clearColor];
    self.searchTextField.placeholder = @"请输入地点";
    self.searchTextField.font =[UIFont fontWithName:FontName size:15];
    [self.searchTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.searchTextField setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"];
    // [self.searchTextField setValue:[UIFont boldSystemFontOfSize:15] forKeyPath:@"_placeholderLabel.font"];
    
    self.searchTextField.delegate = self;
    self.searchTextField.borderStyle = UITextBorderStyleNone;
    self.searchTextField.textColor = [UIColor blackColor];
    self.searchTextField.clearButtonMode = UITextFieldViewModeAlways;
    //}
    self.searchTextField.adjustsFontSizeToFitWidth = YES;
    [borderView addSubview:self.searchTextField];

    _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, kSearchViewHeight, DeviceWidth, DeviceHeight- kNavigationBarHeight- kSearchViewHeight-kSelectLocationLabelHeight)];
    _mapView.showsUserLocation = NO;//先关闭显示的定位图层
    _mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
    _mapView.showsUserLocation = YES;//显示定位图层
    _mapView.zoomLevel = 15;
    [self.view addSubview:_mapView];
    
    //定位
    _locService = [[BMKLocationService alloc] init];
    _locService.delegate = self;
    [_locService startUserLocationService];

    
    _selectLocationLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, DeviceHeight - kSelectLocationLabelHeight-kNavigationBarHeight, DeviceWidth-20, kSelectLocationLabelHeight)];
    _selectLocationLabel.backgroundColor = RGBA(222, 222, 222, 1);
    _selectLocationLabel.text = @"定位中";
    _selectLocationLabel.font = kFont(14);
    _selectLocationLabel.textAlignment = NSTextAlignmentCenter;
    _selectLocationLabel.numberOfLines = 0;
    _selectLocationLabel.adjustsFontSizeToFitWidth = YES;
    _selectLocationLabel.textColor = RGBA(88, 88, 88, 1);
    [self.view addSubview:_selectLocationLabel];
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    //文字改变
    if(textField.text &&textField.text.length>0){
        
        [self searchTextLocationCity:self.cityBt.titleLabel.text content:textField.text];
        
        
    }else{
        self.searchArr = [NSArray array];
        [self.searchTableView reloadData];
    }
    
    
    return YES;
}
- (void)textFieldDidChange:(UITextField *)textField
{
    //文字改变
     if(textField.text &&textField.text.length>0){
         
         BMKSuggestionSearchOption *option = [[BMKSuggestionSearchOption alloc] init];
         option.cityname = self.cityBt.titleLabel.text;
         option.keyword = textField.text;
         BOOL flag = [_searcher suggestionSearch:option];
         if (flag) {
             
         }else{
             NSLog(@"发送失败");
         }
         
         
     }else{
         self.searchArr = [NSArray array];
         [self.searchTableView reloadData];
     }
}

- (void)onGetSuggestionResult:(BMKSuggestionSearch*)searcher result:(BMKSuggestionResult*)result errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        
        
        
        //在此处理正常结果
        NSLog(@"%@",result);
        self.searchArr =[NSArray arrayWithArray:result.keyList];

        if (self.searchArr.count) {
            [self.searchTableView reloadData];
        }
    }
    else {
        NSLog(@"抱歉，未找到结果");
    }
}
- (void)searchTextLocationCity:(NSString *)city content:(NSString *)content
{
    [self.searchTextField resignFirstResponder];
    _searchTableView.hidden = YES;
    BMKCitySearchOption *option = [[BMKCitySearchOption alloc]init];
   // option.pageIndex = 0;
    option.pageCapacity = 50;
    option.city = city;
    option.keyword = content;
    BOOL flag = [_poiSearch poiSearchInCity:option];
    if (flag) {
        NSLog(@"发送成功");
    }
}

#pragma mark BMKPoiSearchDelegate
- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult*)result errorCode:(BMKSearchErrorCode)error
{
    // 清楚屏幕中所有的annotation
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    
    if (error == BMK_SEARCH_NO_ERROR) {
        NSMutableArray *annotations = [NSMutableArray array];
        for (int i = 0; i < result.poiInfoList.count; i++) {
            BMKPoiInfo* poi = [result.poiInfoList objectAtIndex:i];
            BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
            item.coordinate = poi.pt;
            item.title = poi.name;
            item.subtitle = poi.address;
            [annotations addObject:item];
        }
        [_mapView addAnnotations:annotations];
        [_mapView showAnnotations:annotations animated:YES];
    } else if (error == BMK_SEARCH_AMBIGUOUS_ROURE_ADDR){
        NSLog(@"起始点有歧义");
        [HUD Prompt:@"输入位置有歧义"];
    } else {
        // 各种情况的判断。。。
    }
}

- (UITableView *)searchTableView
{
    if (!_searchTableView) {
        _searchTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kSearchViewHeight+kNavigationBarHeight, DeviceWidth, DeviceHeight -kSearchViewHeight-kNavigationBarHeight- self.keyboardHeight) style:UITableViewStylePlain];
        _searchTableView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
        _searchTableView.delegate = self;
        _searchTableView.dataSource = self;
        _searchTableView.scrollsToTop = YES;
//        _searchTableView.contentSize = CGSizeMake(DeviceWidth, DeviceHeight -kSearchViewHeight-kNavigationBarHeight - self.keyboardHeight);
        
         _searchTableView.tableFooterView = [[UIView alloc]init];//不显示空cell
        _searchTableView.separatorColor = RGBA(225, 225, 225, 1);//分隔条颜色
        _searchTableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 51, 0);//滚动条偏移量
        [self.view addSubview:_searchTableView];
        _searchTableView.sectionIndexColor = RGBA(153, 153, 153, 1);//索引颜色
        _searchTableView.sectionIndexBackgroundColor = [UIColor clearColor];//索引未选中背景颜色
        _searchTableView.sectionIndexTrackingBackgroundColor = [UIColor clearColor];//索引选择背景颜色
        
        //
    }
    return _searchTableView;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    
    // Dispose of any resources that can be recreated.
}
#pragma mark BMKLocationServiceDelegate
////处理方向变更信息
//- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
//{
//     [_mapView updateLocationData:userLocation];
//    [HUD Prompt:@"方向变更了"];
//    //NSLog(@"heading is %@",userLocation.heading);
//}
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    
    if (userLocation.location != nil) {
         [_mapView updateLocationData:userLocation];
        NSLog(@"%@,%@",userLocation.title,userLocation.subtitle);
        
        NSLog(@"%@",[NSString stringWithFormat:@"经度:%3.5f\n纬度:%3.5f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude]);
        _mapView.centerCoordinate = userLocation.location.coordinate;
         [_locService stopUserLocationService];
        
       
        
//        //发起反向地理编码检索
//       
        BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[
        BMKReverseGeoCodeOption alloc]init];
        reverseGeoCodeSearchOption.reverseGeoPoint = userLocation.location.coordinate;
        BOOL flag = [_codeSearch reverseGeoCode:reverseGeoCodeSearchOption];
        if(flag)
        {
         // NSLog(@"反geo检索发送成功");
        }
        else
        {
         // NSLog(@"反geo检索发送失败");
        }
        
    }
    
    
   
    //NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
}
//定位失败的时候
- (void)didFailToLocateUserWithError:(NSError *)error
{
    [_locService stopUserLocationService];
    _myLocation = @"";
    [HUD Prompt:@"定位失败,默认城市广州市"];
    [_cityBt setTitle:@"广州市" forState:UIControlStateNormal];
    self.locationCity = @"定位失败";
    
}

#pragma mark BMKGeoCodeSearchDelegate 反解码

//接收反向地理编码结果
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:
(BMKReverseGeoCodeResult *)result
errorCode:(BMKSearchErrorCode)error{
  if (error == BMK_SEARCH_NO_ERROR) {
      
      if (self.userSelect == YES) {
          
          if (_userSelectPointAnnotation) {
              [_mapView removeAnnotation:_userSelectPointAnnotation];
              if (_userSelectPointAnnotation) {
                  _userSelectPointAnnotation = nil;
              }
          }
          
          _userSelectPointAnnotation = [[BMKPointAnnotation alloc]init];
          _userSelectPointAnnotation.coordinate = result.location;
          
          NSString *title;
          NSString *subtitle;
          NSLog(@"%f,%f",result.location.latitude,result.location.longitude);
          if (self.mapPoiText&&self.mapPoiText.length){
              title = [NSString stringWithFormat:@"%@",self.mapPoiText];
              subtitle = [NSString stringWithFormat:@"%@,(%@)",self.mapPoiText,result.address];
              self.mapPoiText = @"";
              
          }else{
              title = [NSString stringWithFormat:@"%@,%@",result.addressDetail.streetName?result.addressDetail.streetName:@"",result.addressDetail.streetNumber?result.addressDetail.streetNumber:@""];
              subtitle = [NSString stringWithFormat:@"%@", result.address];
              
          }
          
          
          _userSelectPointAnnotation.title = title;
          _userSelectPointAnnotation.subtitle =  subtitle;
          [_mapView addAnnotation:_userSelectPointAnnotation];
          _selectLocationLabel.text = subtitle;
          [_cityBt setTitle:result.addressDetail.city forState:UIControlStateNormal];
      }else{
          _myLocation = [NSString stringWithFormat:@"%@", result.address];
          _selectLocationLabel.text = [NSString stringWithFormat:@"%@", result.address];
          [_cityBt setTitle:result.addressDetail.city forState:UIControlStateNormal];
           self.locationCity = result.addressDetail.city;
          NSLog(@"%@",result.addressDetail.city);
      }
      
      
      
     // 在此处理正常结果
  }
  else {
      NSLog(@"抱歉，未找到结果");
  }
    
    self.userSelect = NO;
}

#pragma mark  BMKMapViewDelegate 选中  坐标
- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view
{
    [self.searchTextField resignFirstResponder];
    
    self.mapPoiText = @"";
    [mapView bringSubviewToFront:view];
    [mapView setNeedsDisplay];
    if ([view.annotation.title isEqualToString:@"我的位置"]) {
        _selectLocationLabel.text = _myLocation;
    }else{
        _selectLocationLabel.text = view.annotation.subtitle;
    }
    NSLog(@"%@  %@",view.annotation.title,view.annotation.subtitle);
    
}
/**
 *点中底图标注后会回调此接口
 *@param mapview 地图View
 *@param mapPoi 标注点信息
 */
- (void)mapView:(BMKMapView *)mapView onClickedMapPoi:(BMKMapPoi*)mapPoi
{
    self.mapPoiText = @"";
    //发起反向地理编码检索
    //
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[
                                                            BMKReverseGeoCodeOption alloc]init];
    reverseGeoCodeSearchOption.reverseGeoPoint = mapPoi.pt;
    BOOL flag = [_codeSearch reverseGeoCode:reverseGeoCodeSearchOption];
    if(flag)
    {
        self.userSelect = YES;
        self.mapPoiText = mapPoi.text;
        //NSLog(@"反geo检索发送成功");
    }
    else
    {
       // NSLog(@"反geo检索发送失败");
    }

}

/**
 *点中底图空白处会回调此接口
 *@param mapview 地图View
 *@param coordinate 空白处坐标点的经纬度
 */
- (void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate
{
    
    self.mapPoiText = @"";
    //发起反向地理编码检索
    //
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[
                                                            BMKReverseGeoCodeOption alloc]init];
    reverseGeoCodeSearchOption.reverseGeoPoint = coordinate;
    BOOL flag = [_codeSearch reverseGeoCode:reverseGeoCodeSearchOption];
    if(flag)
    {
        self.userSelect = YES;
        //NSLog(@"反geo检索发送成功");
    }
    else
    {
        //NSLog(@"反geo检索发送失败");
    }
}

///**
// *双击地图时会回调此接口
// *@param mapview 地图View
// *@param coordinate 返回双击处坐标点的经纬度
// */
//- (void)mapview:(BMKMapView *)mapView onDoubleClick:(CLLocationCoordinate2D)coordinate
//{
//    NSLog(@"%f,%f",coordinate.latitude,coordinate.longitude);
//}

///**
// *长按地图时会回调此接口
// *@param mapview 地图View
// *@param coordinate 返回长按事件坐标点的经纬度
// */
//- (void)mapview:(BMKMapView *)mapView onLongClick:(CLLocationCoordinate2D)coordinate
//{
//    NSLog(@"%f,%f",coordinate.latitude,coordinate.longitude);
//}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
